<?php

namespace app\admin\controller\system;

use app\admin\model\system\SystemAttachment as SystemAttachmentModel;
use app\admin\controller\AuthController;
use service\JSYService;
use service\SystemConfigService;
use service\UploadService as Upload;
use service\UtilService;

/**
 * 附件管理控制器
 * Class SystemAttachment
 * @package app\admin\controller\system
 *
 */
class SystemAttachment extends AuthController
{

    /**
     * 编辑器上传图片
     * @return \think\response\Json
     */
    public function upload()
    {
        $res = Upload::image('upfile','editor/'.date('Ymd'));
        //产品图片上传记录
        $fileInfo = $res->fileInfo->getinfo();
        $thumbPath = Upload::thumb($res->dir);
        SystemAttachmentModel::attachmentAdd($res->fileInfo->getSaveName(),$fileInfo['size'],$fileInfo['type'],$res->dir,$thumbPath,0);
        $info = array(
            "originalName" => $fileInfo['name'],
            "name" => $res->fileInfo->getSaveName(),
            "url" => '.'.$res->dir,
            "size" => $fileInfo['size'],
            "type" => $fileInfo['type'],
            "state" => "SUCCESS"
        );
        echo json_encode($info);
    }

    public function index($action){
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("public/system/plug/ueditor/php/config.json")), true);
        switch ($action) {
            case 'config':
                $result =  json_encode($CONFIG);
                break;

            /* 上传图片 */
            case 'uploadimage':
                $result = $this->uploadfile();
                break;
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                $result = $this->uploadfile();
                break;
            /* 上传远程图片 */
            case 'catchimage':
                $result = $this->catchimage();
                break;
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->uploadfile();
                //$result = $this->jsy_upload();
                break;

            /* 列出图片 */
            case 'listimage':
                $result =$this->action_list();
                break;

            default:
                $result = json_encode(array(
                    'state'=> '请求地址出错'
                ));
                break;
        }

        return $result;
    }
    public function action_list($listSize=20)
    {
        /* 返回数据 */
        $result = json_encode([
            "state" => "SUCCESS",
            "list" => [],
            "start" => 0,
            "total" => 0
        ]);
        return $result;
    }

    /**
     * 文件上传
     */
    public function uploadfile()
    {
        try{
            $file = request()->file('upfile');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'files');
            if($info){
                $key = '/public' . DS . 'uploads' . DS . 'files' . DS . $info->getSaveName();
                $key = str_replace('\\','/',$key);
                return json_encode([
                    "originalName" => $file->getInfo('name'),
                    "name"         => $key,
                    "url"          => request()->domain().$key,
                    "state"        => "SUCCESS"
                ]);
            }
            return json_encode([
                "state" => $file->getError()
            ]);
        } catch (\Exception $e) {
            return json_encode(['state'=>$e->getMessage()]);
        }
    }

    /**
     * 远程图片抓取
     */
    public function catchimage()
    {
        try {
            $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("public/system/plug/ueditor/php/config.json")), true);

            /* 上传配置 */
            $config = array(
                "pathFormat" => $CONFIG['catcherPathFormat'],
                "maxSize" => $CONFIG['catcherMaxSize'],
                "allowFiles" => $CONFIG['catcherAllowFiles'],
                "oriName" => "remote.png"
            );
            $fieldName = $CONFIG['catcherFieldName'];

            /* 抓取远程图片 */
            $list = array();
            $post = input();
            $source = $post[$fieldName] ?? [];

            $path = '/public' . DS . 'uploads' . DS . 'files' . DS . date('Ymd') . DS;
            if ( !is_dir(ROOT_PATH . $path) )mkdir($path , 0755);
            foreach ($source as $imgUrl) {
                $ext = pathinfo($imgUrl, PATHINFO_EXTENSION);
                $key = $path . md5($imgUrl) . '.' . $ext;
                if ( file_put_contents(ROOT_PATH . $key, file_get_contents($imgUrl) ) ) {
                    $key = str_replace('\\','/',$key);
                    array_push($list, array(
                        "state"    => 'SUCCESS',
                        "url"      => request()->domain() . $key,
                        "source"   => htmlspecialchars($imgUrl)
                    ));
                }
            }

            /* 返回抓取数据 */
            return json_encode(array(
                'state'=> count($list) ? 'SUCCESS':'ERROR',
                'list'=> $list
            ));
        } catch ( \Exception $e ) {
            return json_encode(['state'=>$e->getMessage()]);
        }

        return json_encode(['state'=> 'ERROR']);
    }

    public function jsy_upload()
    {
        try{
            $file=$this->request->file('upfile');
            $extType=['jpg','jpeg','png','gif'];
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
            $size=2097152;
            if($file->getInfo('size') > $size) return json_encode(['state'=>'上传文件太大不']);
            if(!in_array($ext,$extType)) return json_encode(['state'=>'上传文件类型不符合!请上传JPG,JPEG,PNG,GIF图片']);
            $key = 'image/'.time() . rand(0, 9999) . '.' . $ext;
            $res=JSYService::upLoaderFile($file->getRealPath(),$key);
            if($res['ETag']){
                return json_encode([
                    "originalName" => $file->getInfo('name'),
                    "name" => $key,
                    "url" => 'teaseyoulearn/'.$key,
                    "state" => "SUCCESS"
                ]);
            }else{
                return json_encode([
                    "state" => "ERROR"
                ]);
            }
        }catch (\Exception $e){
            return json_encode(['state'=>$e->getMessage()]);
        }
    }
}
